<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告部分 -->
      <el-alert title="消息提示的文案" type="info" show-icon center :closable="false"></el-alert>
      <!-- 步骤条部分
        active------激活索引号（被激活的前一项自动完成）
      -->
      <el-steps align-center :space="200" :active="activeIndex-0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <!-- 标签页部分 
          before-leave：tabs即将切换时触发的函数，返回值是false将阻止切换
        -->
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="tabsLeave" @tab-click="tabsClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader clearable v-model="addForm.goods_cat" :options="cateList" :props="cascaderProp" @change="cascaderChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :key="i" v-for="(item,i) in manyData" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :key="i2" v-for="(item2,i2) in item.attr_vals" :label="item2"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :key="i" v-for="(item,i) in onlyData" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- <el-form-item> -->
            <!-- 上传图片
                参数：
                on-preview-------点击文件列表中已上传的文件时触发
                :on-remove--------图片移除时触发
                list-type--------图片预览的方式
                on-success-------图片上成功
               -->
            <el-upload :on-success="uploadSuccess" :headers="headerObj" :action="UploadUrl+'upload'" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- </el-form-item> -->
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce" />
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 查看大图 弹出框 -->
    <el-dialog title="图片预览" :visible.sync="pictureDialogVisible" width="50%">
      <img :src="pictureUrl" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>
<script>
import $http from '@/utils/resquest.js'
import _ from 'lodash'
export default {
  data() {
    return {
      // 请求根路径
      UploadUrl: 'http://127.0.0.1:8888/api/private/v1/',
      // 步骤条激活索引
      activeIndex: '0',
      // 添加商品信息表单
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        goods_introduce: '',
        pics: [],
        // 商品参数
        attrs: []
      },
      // 表单验证规则
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'change' }]
      },
      // 商品分类数据
      cateList: [],
      // 选择器配置参数
      cascaderProp: {
        // 次级菜单的展开方式:鼠标悬停/鼠标单击
        expandTrigger: 'hover',
        // 指定选项的值为选项对象的某个属性值
        value: 'cat_id',
        // 指定选项标签为选项对象的某个属性值
        label: 'cat_name',
        // 指定选项的子选项为选项对象的某个属性值
        children: 'children'
      },
      // 参数数据
      manyData: [],
      // 属性数据
      onlyData: [],
      // 上传图片的请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制查看图片对话框
      pictureDialogVisible: false,
      // 查看图片路径
      pictureUrl: ''
    }
  },
  methods: {
    // 添加商品
    async addGoods() {
      // console.log(this.addForm)
      // 深拷贝表单数据
      const form = _.cloneDeep(this.addForm)
      // 把goods_cat转化成字符串
      form.goods_cat = form.goods_cat.join(',')
      // 处理动态参数
      this.manyData.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          // 注意不要忘了改为字符串
          attr_value: item.attr_vals.join(',')
        }
        form.attrs = [...form.attrs, newInfo]
      })

      // 处理静态属性
      this.onlyData.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          // 注意不要忘了改为字符串
          attr_value: item.attr_vals
        }
        form.attrs = [...form.attrs, newInfo]
      })

      console.log(form)
      // 发送请求
      const { data: res } = await $http.post('goods', form)
      console.log(res.data)
      if (res.meta.status !== 201) return this.$message.error('添加失败！')
      console.log('res.data')
      this.$router.push('/goods')
      this.$message.success('添加成功！')
    },
    // 图片上传
    // 图片上成功(参数是服务器响应的数据)
    uploadSuccess(res) {
      if (res.meta.status !== 200) return this.$message.error('上传失败')
      // 拿到服务器返回到图片路径
      const pic = { pic: res.data.tmp_path }
      // 拼接到数组中
      this.addForm.pics = [...this.addForm.pics, pic]
    },
    // 点击文件列表中已上传的文件时触发
    handlePreview(file) {
      this.pictureDialogVisible = true
      this.pictureUrl = file.response.data.url
    },
    // 图片移除时触发
    handleRemove(file) {
      // 拿到对应的图片路径:file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(x => x.pic === file.response.data.tmp_path)
      // 从数组中移除
      this.addForm.pics.splice(index, 1)
    },

    // tabs切换触发
    tabsClick() {
      switch (this.activeIndex) {
        case '1':
          this.getManyData()
          break
        case '2':
          this.getOnlyData()
          break
        default:
          console.log(this.activeIndex)
          break
      }
    },
    // 获取商品属性
    async getOnlyData() {
      // console.log('当前id' + this.cateId)
      const { data: res } = await $http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
      if (res.meta.status !== 200) return this.$message.error('数据获取失败！')
      // console.log(res.data)
      this.onlyData = res.data
    },
    // 获取商品参数
    async getManyData() {
      // console.log('当前id' + this.cateId)
      const { data: res } = await $http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
      if (res.meta.status !== 200) return this.$message.error('数据获取失败！')
      // 把参数转换成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
      })
      // console.log(res.data)
      this.manyData = res.data
    },
    // tabs即将切换时，判断信息是否完整
    tabsLeave() {
      let flag = true
      this.$refs.addFormRef.validate(v => {
        if (!v) {
          flag = false
          return this.$message.error('请将信息填写完整！')
        }
      })
      return flag
    },
    // 选择器发生改变时
    cascaderChange() {
      console.log(this.addForm.goods_cat)
      // 如果选择的不是三级分类就清空数组
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 获取商品分类信息
    async getCateList() {
      const { data: res } = await $http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('数据获取失败！')
      // console.log(res.data)
      this.cateList = res.data
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 计算选择器发生变化时，对应分类的id
    cateId() {
      if (this.addForm.goods_cat.length !== 3) return null
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    }
  }
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.addBtn {
  margin-top: 10px;
}
</style>